package org.duomn.ichat.net.impl;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.duomn.ichat.entity.FileMessage;
import org.duomn.ichat.entity.Message;
import org.duomn.ichat.exception.MsgLoseException;
import org.duomn.ichat.net.AbstractMsgSender;
import org.duomn.ichat.util.Const;
import org.duomn.ichat.util.IOUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FileMsgSender extends AbstractMsgSender {
	
	private static Logger logger = LoggerFactory.getLogger(FileMsgSender.class);
	
	@Override
	public void send(Object obj) throws MsgLoseException {
		FileMessage fileMsg = (FileMessage) obj;
		if (fileMsg.fileMsgType == FileMsgType.FILE_TRAN_HEAD) { // 发送文件.分为两部分
			File file = (File) fileMsg.data;
			// 1.发送标示该传输对象为文件
			try {
				out.writeObject(fileMsg); 
			} catch (IOException e) {
				String expInfo = "Send file stream head happened exception!";
				logger.error(expInfo, e);
				throw new MsgLoseException(expInfo, fileMsg);
			}
			// 2.向流中开始写入文件
			BufferedInputStream in = null;
			try {
				in = new BufferedInputStream(new FileInputStream(file));
				IOUtil.copyStream(in, out);
			} catch (FileNotFoundException e) {
				logger.error("The transfer file not exists!", e);
			} catch (IOException e) {
				logger.error("Transfer file happend IOException!", e);
			} finally {
				if (in != null) {
					try {
						in.close();
					} catch (IOException e) {
						logger.error("Close the file input stream happend exception!", e);
					}
				}
			}
		} else { // 对于文件信息，同意文件接受，拒绝文件接受，采用相同方式发送
			try {
				out.writeObject(fileMsg);
			} catch (IOException e) {
				String errInfo = "The file information send exceptin!";
				logger.error(errInfo, e);
				throw new MsgLoseException(errInfo, fileMsg);
			}
		} 
	}

	@Override
	public void sendClose() throws MsgLoseException {
		Message message = new Message();
		message.src = Const.get(Const.USER_SELF_ID);
		send(message);
	}

}
